using Godot;
using Godot.Collections;
using System;
using System.Collections.Generic;
using System.Net;

public class Player : KinematicBody2D
{
    enum face
    {
        left = 0, right = 1
    }
    public BaseSpeed SpeedConfig = new BaseSpeed();
    public Vector2 velocity = new Vector2();
    public double fallhigh = 0;
    public Vector2 lastvelocity = new Vector2();
    public Vector2 LastLocation = new Vector2();
    public Vector2 LastChunkLocation = new Vector2();
    private bool Fly = false;
    private int gamemode = 0;
    private int TochRange = 10;
    public PlayerStore store = new PlayerStore();
    public int layer = 0;
    //现金
    public int Cash = 0;
    //生命值
    public double Health = 10;
    public double MaxHealth = 10;
    //饱食度
    public double Satiety = 10;
    public double MaxSatiety = 10;
    //体力值
    public double Stamina = 100;
    public double MaxStamina = 100;


    //
    public BlockWorld world;
    public static Camera2D camera;
    public AnimationPlayer animation;
    public AnimationTree animationTree;
    public CollisionShape2D Collision;
    public Sprite body;
    public TextureRect HandItem;
    public Sprite CursorSprite, Chunkgird;
    public View view;
    public RayCast2D rcleft, lt, rcright, rt, up, down, tl, tr;
    public override void _Ready()
    {
        world = GetOwner<BlockWorld>();
        camera = GetNode<Camera2D>("Camera2D");
        CursorSprite = GetNode<Sprite>("CursorSprite");
        Chunkgird = GetNode<Sprite>("Chunkgird");
        Collision = GetNode<CollisionShape2D>("Collision");
        view = GetNode<View>("View");
        body = GetNode<Sprite>("Body");
        HandItem = GetNode<TextureRect>("Body/Arm2/HandItem");
        animation = GetNode<AnimationPlayer>("AnimationPlayer");
        animationTree = GetNode<AnimationTree>("AnimationTree");
        animationTree.Get("parameters/playback");
        rcleft = GetNode<RayCast2D>("left");
        rcright = GetNode<RayCast2D>("right");
        lt = GetNode<RayCast2D>("lt");
        rt = GetNode<RayCast2D>("rt");
        up = GetNode<RayCast2D>("up");
        down = GetNode<RayCast2D>("down");
        tl = GetNode<RayCast2D>("tl");
        tr = GetNode<RayCast2D>("tr");

        SetGamemode(0);
        Load();
        RegisterCommand();

    }
    public void RegisterCommand()
    {
        view.console.AddCommand(new CommandaData("gamemode", (List<string> data) =>
        {
            if (data != null)
            {
                int gm = 0;
                if (int.TryParse(data[0], out gm) && gm <= 1)
                {
                    SetGamemode(gm);
                    if (gm == 0) view.console.SendMessage($"更改游戏模式为: 生存模式", false);
                    if (gm == 1) view.console.SendMessage($"更改游戏模式为: 创造模式", false);
                }
                else
                {
                    view.console.SendMessage($"参数错误:{gm}必须是合法的数字".Color("red"), false);
                }

            }
            else
            {
                return false;
            }
            return true;
        }));
    }
    public override void _Input(InputEvent @event)
    {

        if (view.console.Visible)
        {

        }
        else
        {
            if (Input.IsActionJustPressed("console"))
            {
                view.console.open();
            }

            velocity.x = 0;
            float walk = SpeedConfig.walk;
            if (Input.IsActionPressed("ctrl"))
                walk = SpeedConfig.run;

            if (Input.IsActionJustPressed("open") && !IsOpeningView())
            {
                Vector3I position = GetCursor();
                BlockData block = world.GetBlock(position);
                BlockMaterial bm = block.GetMaterial();
                if (bm.UseEvent != null)
                {
                    PlayerUseBlockEvent e = new PlayerUseBlockEvent(this, world, position)
                    {
                        block = block
                    };
                    if (bm.UseEvent(e))
                    {
                        return;
                    }
                }
                else
                {
                    bm = block.GetMaterial();
                    if (bm.UseEvent != null)
                    {
                        PlayerUseBlockEvent e = new PlayerUseBlockEvent(this, world, position)
                        {
                            block = block
                        };
                        if (bm.UseEvent(e))
                        {
                            return;
                        }
                    }
                }
            }
            if (Input.IsActionJustPressed("rotate"))
            {
                BlockData block = world.GetBlock(GetCursor());
                BlockMaterial bm = block.GetMaterial();
                if (bm.RotateMax > 0 && bm.StateMax > 0)
                {
                    block.SetRotate(block.Rotate + 1);
                    if (block.Rotate >= bm.RotateMax)
                    {
                        block.Rotate = 0;
                    }
                    if (bm.RotateEvent != null)
                    {
                        Vector3I v = GetCursor();
                        PlayerRotateBlockEvent e = new PlayerRotateBlockEvent(this, world, new Vector3I(v.Z, v.Y, v.Z));
                        e.block = block;
                        bm.RotateEvent(e);
                    }
                }

            }

            if (gamemode == 0)
            {
                if (Input.IsActionPressed("a"))
                {
                    if (rcleft.IsColliding() && !lt.IsColliding() && !tl.IsColliding())
                    {
                        SetPosition(new Vector2(Position.x, Position.y - 17));
                        //velocity.y = -SpeedConfig.jump;
                    }
                    velocity.x = -walk;
                    SetFace(((int)face.left));
                    animation.Play("run");
                }
                else
                if (Input.IsActionPressed("d"))
                {
                    if (rcright.IsColliding() && !rt.IsColliding() && !tr.IsColliding())
                    {
                        SetPosition(new Vector2(Position.x, Position.y - 17));
                        //velocity.y = -SpeedConfig.jump;
                    }
                    velocity.x = walk;
                    SetFace(((int)face.right));
                    animation.Play("run");
                }
                else
                {
                    animation.Play("idle");
                }
                if (Input.IsActionJustPressed("q"))
                {
                    PackedScene ps = GD.Load<PackedScene>("res://Tscn/ItemEntity.tscn");
                    ItemEntity e = ps.Instance<ItemEntity>();
                    world.AddChild(e);
                    e.SetPosition(this.Position);
                }
                if (Input.IsActionJustPressed("shift") && IsOnFloor())
                {
                    if (down.IsColliding())
                    {
                        BlockData block = world.GetBlock(GetLocation() + new Vector3I(0, -1));
                        if (block.Name == "half_wood_plank")
                        {
                            BlockData b1 = world.GetBlock(GetLocation() + new Vector3I(0, -2));
                            BlockData b2 = world.GetBlock(GetLocation() + new Vector3I(0, -3));
                            if (b2.Name == "air" && b1.Name == "air")
                            {
                                Position = new Vector2(Position.x, Position.y + 49);
                                velocity.y = 0;
                            }

                        }
                    }
                }
                if ((Input.IsActionJustPressed("space") || Input.IsActionJustPressed("w")) && IsOnFloor())
                {
                    velocity.y = -SpeedConfig.jump;
                    if (up.IsColliding())
                    {
                        BlockData block = world.GetBlock(GetLocation() + new Vector3I(0, 2));
                        if (block.Name == "half_wood_plank")
                        {
                            BlockData b1 = world.GetBlock(GetLocation() + new Vector3I(0, 3));
                            BlockData b2 = world.GetBlock(GetLocation() + new Vector3I(0, 4));
                            if (b2.Name == "air" && b1.Name == "air")
                            {
                                SetPosition(new Vector2(Position.x, Position.y - 49));
                                velocity.y = 0;
                            }

                        }
                    }
                }
                else if ((Input.IsActionPressed("space") || Input.IsActionPressed("w")) && CanSwim())
                {
                    velocity.y = -SpeedConfig.swim;
                }
            }
            else if (gamemode == 1)
            {
                if (Input.IsActionPressed("a"))
                {
                    velocity.x = -walk;
                    SetFace((int)face.left);
                    animation.Play("run");
                }
                else
                if (Input.IsActionPressed("d"))
                {
                    velocity.x = walk;
                    SetFace((int)face.right);
                    animation.Play("run");
                }
                else
                if (Input.IsActionJustPressed("w") || Input.IsActionPressed("w"))
                {
                    velocity.y = -walk;
                    animation.Play("run");
                }
                else
                if (Input.IsActionJustPressed("s") || Input.IsActionPressed("s"))
                {
                    velocity.y = walk;
                    animation.Play("run");
                }
                else
                {
                    animation.Play("idle");
                }
            }
            if (Input.IsActionJustPressed("e"))
            {
                if (view.HasOpenView())
                {
                    view.CloseOpenView();
                }
                else
                {
                    if (gamemode == 0)
                    {
                        view.SetOpenView(GD.Load<PackedScene>("res://Tscn/Store/BackPack.tscn").Instance<BackPack>());
                    }
                    if (gamemode == 1)
                    {
                        view.SetOpenView((StoreView)GD.Load<PackedScene>("res://Tscn/Store/CreativeBackPack.tscn").Instance<CreativeBackPack>());
                    }

                }
                // if (view.backPack.state) view.backPack.Close();
                // else view.backPack.Open();
            }
            //

            if (Input.IsActionPressed("f3"))
            {
                view.SetInfoVisible(!view.GetInfoVisible());
            }
            if (Input.IsActionPressed("f2"))
            {
                Chunkgird.Visible = !Chunkgird.Visible;
            }
            if (Input.IsActionPressed("chat"))
            {

            }
            if (Input.IsActionPressed("command"))
            {

            }
            if (Input.IsActionPressed("send"))
            {

            }
            if (Input.IsActionJustPressed("tap"))
            {
                if (layer == 0) layer = 1;
                else layer = 0;

                store.breaKing.Reset();
            }
            //
            if (Input.IsActionJustPressed("1")) store.setIndex(0);
            if (Input.IsActionJustPressed("2")) store.setIndex(1);
            if (Input.IsActionJustPressed("3")) store.setIndex(2);
            if (Input.IsActionJustPressed("4")) store.setIndex(3);
            if (Input.IsActionJustPressed("5")) store.setIndex(4);
            if (Input.IsActionJustPressed("6")) store.setIndex(5);
            if (Input.IsActionJustPressed("7")) store.setIndex(6);
            if (Input.IsActionJustPressed("8")) store.setIndex(7);
            if (Input.IsActionJustPressed("9")) store.setIndex(8);
            if (Input.IsActionJustPressed("mu"))
            {
                store.setIndex(store.getIndex() - 1);
            }
            if (Input.IsActionJustPressed("md"))
            {
                store.setIndex(store.getIndex() + 1);
            }
        }



    }
    public override void _PhysicsProcess(float delta)
    {
        lastvelocity = new Vector2(velocity);
        bool cs = CanSwim();
        if (cs)
        {
            velocity.y += SpeedConfig.gravity / 4 * delta;
        }
        if (!Fly && !cs)
        {
            velocity.y += SpeedConfig.gravity * delta;
        }

        velocity = MoveAndSlide(velocity, Vector2.Up);
        if (Fly)
            velocity.y = 0;

        store.UpdataRecipe();
        view.hotBar.Updata();
        view.UpdataOpenView(this);
        view.CursorSlot.SetItemStack(store.CursourItem);
        store.Updata = false;





        if (Input.IsActionJustPressed("use") && !IsOpeningView())
        {
            Vector3I position = GetCursor();
            BlockData block = world.GetBlock(position);
            BlockMaterial bm = block.GetMaterial();
            if (bm.UseEvent != null)
            {
                PlayerUseBlockEvent e = new PlayerUseBlockEvent(this, world, position)
                {
                    block = block
                };
                if (bm.UseEvent(e))
                {
                    return;
                }
            }
            else
            {
                block = world.GetBlock(position);
                bm = block.GetMaterial();
                if (bm.UseEvent != null)
                {
                    PlayerUseBlockEvent e = new PlayerUseBlockEvent(this, world, position)
                    {
                        block = block
                    };
                    if (bm.UseEvent(e))
                    {
                        return;
                    }
                }
            }
        }
        else
        if (Input.IsActionPressed("use") && !IsOpeningView())
        {
            Vector3I v1 = GetCursor();
            PlaceBlock(v1);
        }



        if (Input.IsActionPressed("click") && !IsOpeningView())
        {
            Vector3I position = GetCursor();
            Vector3I v2 = GetLocation();
            double i1 = Math.Abs(position.X - v2.X);
            double i2 = Math.Abs(position.Y - v2.Y);
            double i3 = i1 + i2;
            if (i3 > TochRange)
            {
                return;
            }

            if (position.X < v2.X) SetFace(0);
            else if (position.Y > v2.Y) SetFace(1);

            BlockData block = world.GetBlock(position);
            if (block == null)
            {
                return;
            }

            BlockMaterial bm = block.GetMaterial();
            if (!bm.CanBreak)
            {
                store.breaKing.Reset();
                return;
            }



            animation.Play("break");
            if (store.breaKing.GetBreaking())
            {
                if (store.breaKing.Updata(position, delta))
                {
                    /*                    if (gamemode == 1)
                                        {
                                            BreakRoundBlock(store.breaKing.location, 2);
                                        }
                                        else*/
                    {
                        BreakBlock(store.breaKing.location);
                    }
                    // BreakBlock(v1);
                    store.breaKing.Reset();
                }

            }
            else
            {
                if (gamemode == 0 && Stamina > 0)
                {
                    if (
                        store.GetItemStack(store.getIndex()) != null &&
                        store.GetItemStack(store.getIndex()).itemData != null &&
                        store.GetItemStack(store.getIndex()).itemData is ToolData
                        )
                    {
                        ToolData td = (ToolData)store.GetItemStack(store.getIndex()).itemData;
                        if (td.tool.type == bm.tool.type || bm.tool.type == ToolType.Hand)
                        {
                            if (td.tool.level >= bm.tool.level)
                                store.breaKing.Set(position, bm.Durable, (1f + (float)td.tool.level / 2f));
                            else
                            {
                                store.breaKing.Set(position, bm.Durable, 1f / bm.tool.punish);
                            }
                        }
                        else
                        {
                            store.breaKing.Set(position, bm.Durable, 1f / bm.tool.punish);
                        }

                    }
                    else
                    {
                        if (bm.tool.type == ToolType.Hand)
                        {
                            store.breaKing.Set(position, bm.Durable, 1);
                        }
                        else
                        {
                            store.breaKing.Set(position, bm.Durable, 1f / bm.tool.punish);
                        }

                    }


                }
                if (gamemode == 1) store.breaKing.Set(position, 0, 0);
            }
        }
        else
        {
            store.breaKing.Reset();
        }
    }
    public override void _Process(float delta)
    {
        UpdtaHandItem();

        view.hpBar.SetHealth((int)Health, (int)MaxHealth);
        view.Layer.Frame = layer;

        view.statePanel.UpdataHp((int)Health, (int)MaxHealth);
        view.statePanel.UpdataHg((int)Satiety, (int)MaxSatiety);
        view.statePanel.UpdataStamina((int)Stamina, (int)MaxStamina);
        view.statePanel.UpdataCash(Cash);


        Vector2 rpos = ((GetMousePosition() / 16).Floor()) * 16;
        CursorSprite.GlobalPosition = rpos;
        CursorSprite.Frame = layer * 9 + store.breaKing.getPace();
        Vector3I v = GetCursor();
        BlockData block = world.GetBlock(v);

        view.blockDataInfo.SetBlock(block);

        if (block != null && block.GetMaterial().View)
        {
            CursorSprite.GetNode<Sprite>("KeyHelp").Visible = true;
        }
        else
        {
            CursorSprite.GetNode<Sprite>("KeyHelp").Visible = false;
        }


        if (Chunkgird.Visible)
        {
            var cgpos = ((GetChunkG() - new Vector2(1, 1)) * 16 * 16) + new Vector2(0, 16);
            Chunkgird.GlobalPosition = cgpos;
        }
        view.CursorSlot.MoveToMouse();
        Vector3I ppos = GetLocation();
        Vector2 cpos = GetChunk();
        Vector3I cupos = GetCursor();
        view.ClearInfo().
        AddInfo("").
        AddInfo($"{"fps".Color("red")}:[{Engine.GetFramesPerSecond().ToString().Color("black")}]".ToRight()).
        AddInfo($"{"tps".Color("green")}:[{world.tps.ToString().Color("black")}]".ToRight()).
        AddInfo($"鼠标 [{(int)cupos.X},{(-(int)cupos.Y)}]".ToRight()).
        AddInfo($"坐标 [{(int)ppos.X},{((int)ppos.Y)}]".ToRight());
    }
    public void Fall(double high)
    {
        int hp = (int)(high / 16f);
        if (hp > 3) Health -= (hp - 3);
    }
    public void BreakBlock(Vector3I location)
    {
        bool drop = false;
        BlockData block = world.GetBlock(location);
        if (block.Name == "air") return;
        BlockMaterial bm = block.GetMaterial();
        List<ItemStack> drops = block.GetMaterial().GetDrop();
        PlayerBreakBlockEvent pbe = new PlayerBreakBlockEvent(this, world, location)
        {
            block = block
        };
        if (bm.BreakEvent == null || bm.BreakEvent(pbe))
        {
            if (
                store.GetItemStack(store.getIndex()) != null &&
                store.GetItemStack(store.getIndex()).itemData != null &&
                store.GetItemStack(store.getIndex()).itemData is ToolData
                )
            {
                ToolData td = (ToolData)store.GetItemStack(store.getIndex()).itemData;
                if (bm.tool.type == ToolType.Hand || bm.tool.type == td.tool.type || bm.tool.drop)
                {
                    drop = true;
                }
                else
                {
                    drop = false;
                }

                if (td.Durable > 0)
                    td.SubDurable(1);
                if (td.Durable <= 0)
                {
                    store.SubAmount(store.getIndex(), 1);
                }

            }
            else if (bm.tool.type == ToolType.Hand)
            {
                drop = true;
            }
            else if (bm.tool.drop) drop = true;
            //ItemStack item = new ItemStack(block.GetItemMaterial());
            if (drop) store.AddItems(drops);

            world.SetBlock(location, Materials.Air);

            Stamina -= 1;


            //world.SpawnFloatingText((int)Position.x, (int)Position.y + 32, $"{"体力".Color("yellow")}{"-"}{"1".Color("yellow")}");
        }
    }
    public void PlaceBlock(Vector3I position)
    {
        bool CanPlace = true;
        if (store.CursourItem != null)
        {
            ItemMateria im = store.CursourItem.getMaterial();
            if (im.PlayerUseItem != null)
            {
                PlayerUseItemEvent puie = new PlayerUseItemEvent(this, store.CursourItem, world, position);
                puie.block = world.GetBlock(position);
                puie.slotType = PlayerUseItemEvent.PlayerUseItemSlotType.Curosr;
                CanPlace = im.PlayerUseItem(puie);
            }
        }
        else if (store.GetItemStack(store.getIndex()) != null)
        {
            ItemMateria im = store.GetItemStack(store.getIndex()).getMaterial();
            if (im.PlayerUseItem != null)
            {
                PlayerUseItemEvent puie = new PlayerUseItemEvent(this, store.GetItemStack(store.getIndex()), world, position);
                puie.block = world.GetBlock(position);
                puie.slotType = PlayerUseItemEvent.PlayerUseItemSlotType.Hand;
                CanPlace = im.PlayerUseItem(puie);
            }
        }

        BlockData block = world.GetBlock(position);
        if (block.GetMaterial().CanReplace && CanPlace)
        {
            if (store.CursourItem != null && store.CursourItem.getMaterial().isblock)
            {
                store.Updata = true;
                world.SetBlock(position, store.CursourItem.getBlockMaterial());
                if (gamemode == 0) store.SubCurosrItemAmount(1);

                animation.Play("place");
            }
            else
            {
                ItemStack item = store.GetItemStack(store.getIndex());
                if (item != null && item.getMaterial().isblock)
                {
                    world.SetBlock(position, item.getBlockMaterial());
                    if (gamemode == 0) store.SubAmount(store.getIndex());
                    animation.Play("place");
                }
            }
        }
        return;
    }
    public void RightClickStore(Slot slot)
    {
        if (store.CursourItem == null)
        {
            if (slot.Type == SlotType.Craft)
            {
                ItemStack item = store.GetItemStack(slot.index);
                if (item != null)
                {
                    store.CursourItem = item;
                    store.SetItem(slot.index, null);
                }
                return;
            }
            if (store.GetItemStack(slot.index) == null) return;
            //拾取一半
            int amount = store.GetItemStack(slot.index).Amount;
            int halfAmount = amount / 2;
            int otherAmount = amount - halfAmount;

            if (amount == 1)
            {
                halfAmount = 0;
                otherAmount = 1;
            }
            store.CursourItem = new ItemStack(store.GetItemStack(slot.index).getMaterial());
            store.CursourItem.Amount = otherAmount;
            store.SetAmount(slot.index, halfAmount);
        }
        else
        {
            if (slot.Type == SlotType.Craft)
            {
                return;
            }

            //放置一个
            if (store.GetItemStack(slot.index) != null)
            {
                ItemStack target = store.GetItemStack(slot.index);
                if (
                    target.Name ==
                    store.CursourItem.Name
                )
                {
                    if (!target.IsFull())
                    {
                        store.AddAmount(slot.index, 1);
                        store.SubCurosrItemAmount(1);
                    }
                }
            }
            else
            {
                store.SetItem(slot.index, new ItemStack(store.CursourItem.getMaterial()));
                store.SubCurosrItemAmount(1);
            }
        }
    }
    public void ShiftClickStore(Slot slot)
    {
        if (store.CursourItem == null)
        {
            if (slot.Type == SlotType.Craft)
            {
                int max = store.GetCraftMax();
                for (int m = 0; m < max; m++)
                {
                    for (int i = 36; i < 40; i++)
                    {
                        if (store.GetItemStack(i) != null)
                        {
                            store.SubAmount(i);
                        }
                    }

                    store.QuikToStore(slot.index);
                    store.UpdataRecipe();
                }


            }
            else
            {
                store.QuikToStore(slot.index);
            }

        }
    }
    public void ClickStore(Slot slot)
    {
        if (store.CursourItem == null)
        {
            //拾取
            store.CursourItem = store.GetItemStack(slot.index);
            if (slot.Type == SlotType.Craft && store.CursourItem != null)
            {
                for (int i = 36; i < 40; i++)
                {
                    if (store.GetItemStack(i) != null)
                    {
                        store.SubAmount(i);
                    }
                }
                store.UpdataRecipe();
            }
            store.Remove(slot.index);
        }
        else
        {
            if (store.GetItemStack(slot.index) != null)
            {
                ItemStack target = store.GetItemStack(slot.index);
                if (
                    target.Name ==
                    store.CursourItem.Name
                )
                {//放置
                    if (slot.Type == SlotType.Craft)
                    {
                        for (int i = 36; i < 40; i++)
                        {
                            if (store.GetItemStack(i) != null)
                            {
                                store.SubAmount(i);
                            }
                        }
                        store.CursourItem.AddAmount(1);
                        store.UpdataRecipe();
                    }
                    else
                    {
                        int i = store.AddAmount(slot.index, store.CursourItem.Amount);
                        store.SetCurosrItemAmount(i);
                    }

                }
                else
                {//交换
                    ItemStack item = store.GetItemStack(slot.index);
                    store.SetItem(slot.index, store.CursourItem);
                    store.CursourItem = item;
                }

            }
            else
            {//放置
                if (slot.Type == SlotType.Craft)
                {

                }
                else
                {
                    store.SetItem(slot.index, store.CursourItem);
                    store.CursourItem = null;
                }

            }
        }
    }






    public void SetFace(int face)
    {
        if (face == 0)
            body.SetScale(new Vector2(1, 1));
        else body.SetScale(new Vector2(-1, 1));
    }
    public Vector2 GetMousePosition()
    {
        Vector2 ofs = (GetViewport().Size / 2) * camera.Zoom;
        Vector2 mousepos = GetViewport().GetMousePosition() * camera.Zoom + Position - ofs;
        return mousepos;
    }
    public Vector3I GetCursor()
    {
        Vector2 pos = GetMousePosition() / 16;
        return new Vector3I(pos.Floor() * new Vector2(1, -1), layer);
    }
    public Vector2 GetChunk()
    {
        Vector2 pos = GlobalPosition / (16 * 16);
        return pos.Floor() * new Vector2(1, -1);
    }
    public Vector2 GetChunkG()
    {
        Vector2 pos = GlobalPosition / (16 * 16);
        return pos.Floor();
    }
    public Vector3I GetLocation()
    {
        Vector2 pos = Position / 16;
        return new Vector3I(pos.Floor() * new Vector2(1, -1), 1);
    }
    public void UpdtaHandItem()
    {
        if (store.CursourItem != null)
        {
            HandItem.Texture = store.CursourItem.getMaterial().texture;
        }
        else if (store.GetItemStack(store.getIndex()) != null)
        {
            if (store.GetItemStack(store.getIndex()).getMaterial() == null)
            {
                //GD.Print(store.GetItemStack(store.getIndex()).Name);
            }
            HandItem.Texture = store.GetItemStack(store.getIndex()).getMaterial().texture;
        }
        else
        {
            HandItem.Texture = null;
        }
    }

    public bool CanSwim()
    {
        BlockData blockData = world.GetBlock(GetLocation());
        if (blockData != null && blockData.GetMaterial().Name == "water")
        {
            return true;
        }
        return false;
    }


    //
    public void SetGamemode(int g)
    {
        gamemode = g;
        switch (g)
        {
            case 0:
                {
                    SetFly(false);
                    break;
                }
            case 1:
                {
                    SetFly(true);
                    break;
                }
        }
    }
    public void SetFly(bool fly)
    {
        if (fly)
        {

            Collision.Disabled = true;
        }
        else
        {
            Collision.Disabled = false;
        }

        Fly = fly;
    }
    public void OpenBackPack()
    {
        if (view.HasOpenView())
        {
            view.CloseOpenView();
        }
        else
        {
            view.SetOpenView(GD.Load<PackedScene>("res://Tscn/Store/BackPack.tscn").Instance<BackPack>());
        }

    }
    public bool IsOpeningView()
    {
        if (view.HasOpenView()) return true;
        if (view.console.IsVisible()) return view.console.IsVisible();
        return false;
    }
    public Dictionary GetDictionary()
    {
        Dictionary dict = new Dictionary();
        dict.Add("Frame", Scale.x);
        dict.Add("Position.x", Position.x);
        dict.Add("Position.y", Position.y);
        dict.Add("Store", store.getDict());
        dict.Add("Gamemode", gamemode);
        return dict;
    }
    public String toJson()
    {
        return JSON.Print(GetDictionary());
    }
    public void Save()
    {
        Directory dir = new Directory();
        if (!dir.DirExists("Save"))
        {
            dir.MakeDir("Save");
        }
        if (!dir.DirExists($"Save/{BlockWorld.WorldName}/"))
        {
            dir.MakeDir($"Save/{BlockWorld.WorldName}/");
        }
        File f = new File();
        f.OpenCompressed($"Save/{BlockWorld.WorldName}/player.data", File.ModeFlags.Write);
        f.StoreVar(GetDictionary());
        f.Close();
    }
    public void Load()
    {
        File f = new File();
        if (!f.FileExists($"Save/{BlockWorld.WorldName}/player.data"))
        {
            return;
        }

        f.OpenCompressed($"Save/{BlockWorld.WorldName}/player.data", File.ModeFlags.Read);
        Dictionary dict = (Dictionary)f.GetVar();
        f.Close();
        int x = dict["Position.x"].ToInt();
        int y = dict["Position.y"].ToInt();
        SetGamemode(dict["Gamemode"].ToInt());
        Position = new Vector2(x, y);
        Scale = new Vector2(dict["Frame"].ToInt(), Scale.y);
        store.JsonTo((Dictionary)dict["Store"]);
    }

    public override void _ExitTree()
    {
        Save();
    }
    public override void _EnterTree()
    {
    }

    public void AutoSave()
    {
        Save();
    }

    public void PerSecond()
    {
        if (gamemode == 0)
        {
            if (Stamina < MaxStamina)
            {
                Stamina += 0.1;
                if (Stamina > MaxStamina) Stamina = MaxStamina;
                Satiety -= 0.01;


                //world.SpawnText((int)Position.x,(int)Position.y-32,$"{"体力".Color("yellow")}{"+"}{"0.1".Color("green")}");
            }
        }

    }
}
